<template>
	<div class="app-container">
		<el-form :inline="true" :model="dataForm" @submit.native.prevent @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input placeholder="请输入方案编号搜索" v-model="dataForm.projectId" :clearable="true" size="mini">
          <template slot="prepend">方案编号</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="请输入方案名称搜索" v-model="dataForm.projectName" :clearable="true" size="mini">
          <template slot="prepend">方案名称</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="请输入货品名称搜索" v-model="dataForm.productName" :clearable="true" size="mini">
          <template slot="prepend">货品名称</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="请输入物料编码搜索" v-model="dataForm.productGmp" :clearable="true" size="mini">
          <template slot="prepend">物料编码</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="pan-btn primary-btn" size="mini" @click="searchData()" icon="el-icon-search">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isAuth('base:stability:save')" @click="addModule()" type="success" class="pan-btn success-btn" size="mini" icon="el-icon-upload">新增</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="isAuth('base:stability:delete')" @click="deleteData()" type="danger" class="pan-btn danger-btn" size="mini" icon="el-icon-delete">删除</el-button>
      </el-form-item>
    </el-form>

		<el-table
			:data="dataList"
			v-loading="dataListLoading"
			border
      fit
      highlight-current-row
			@selection-change="selectionChange"
	    style="width: 100%">
    <el-table-column
      type="selection"
      header-align="center"
      align="center"
      width="50">
    </el-table-column>
    <el-table-column
			prop="projectId"
			header-align="center"
			align="center"
			label="方案编号">
		</el-table-column>
		<el-table-column
			prop="projectName"
			header-align="center"
			align="center"
			label="方案名称">
		</el-table-column>
    <el-table-column
    	prop="stabilityModeName"
    	header-align="center"
    	align="center"
    	label="考察方式">
    </el-table-column>
    <el-table-column
    	prop="batchQuantity"
    	header-align="center"
    	align="center"
    	label="样品数量">
      <template slot-scope="{row}">
        <span>{{ row.batchQuantity + row.batchUnitName + '/批' }}</span>
      </template>
    </el-table-column>
    <el-table-column
    	prop="checkPeriodValue"
    	header-align="center"
    	align="center"
    	label="检测周期">
      <template slot-scope="{row}">
        <span>{{ row.checkPeriodValue + row.checkPeriodTimeName }}</span>
      </template>
    </el-table-column>
    <el-table-column
    	prop="checkFrequency"
    	header-align="center"
    	align="center"
    	label="检测频率">
    </el-table-column>
    <el-table-column
    	prop="pack"
    	header-align="center"
    	align="center"
    	label="包装">
    </el-table-column>
    <el-table-column
    	prop="storeEnv"
    	header-align="center"
    	align="center"
    	label="贮藏">
    </el-table-column>
    <el-table-column
    	prop="envT"
    	header-align="center"
    	align="center"
    	label="温度">
    </el-table-column>
    <el-table-column
    	prop="envH"
    	header-align="center"
    	align="center"
    	label="湿度">
    </el-table-column>
    <el-table-column
    	prop="remark"
    	header-align="center"
    	align="center"
    	label="备注">
    </el-table-column>
		<el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
        width="220">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="getTimeData(scope.$index)">查看</el-button>
          <el-button v-if="isAuth('base:stability:collocate')" type="text" size="small" @click="collocate(scope.row)">配置</el-button>
          <el-button v-if="isAuth('base:stability:update')" type="text" size="small" @click="updateData(scope.row)">修改</el-button>
          <el-button v-if="isAuth('base:stability:delete')" type="text" size="small" @click="deleteData(scope.row.projectId)">删除</el-button>
          <el-button v-if="isAuth('base:stability:copy')" type="text" size="small" @click="copy(scope.row.projectId)">复制</el-button>
          <el-button v-if="isAuth('base:stability:sync')" type="text" size="small" @click="sync(scope.row.projectId)">同步</el-button>
        </template>
      </el-table-column>
		</el-table>
		<el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog
      :visible.sync="showTimeData"
      :before-close="closeTimeData"
      append-to-body
      close-on-click-modal
      width="60%">
      <el-table :data="timeData">
        <el-table-column width="70" label="取样点">
          <template slot-scope="{row}">
            <span>{{ row.timeValue + row.timeName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考察项目">
          <template slot-scope="{row}">
            <span v-for="(s,i) in row.standards" :key="i">
              <span style="color: #D4B249" v-html="s.nationInspectionStandardNum + ':'"></span><br>
              <span>{{ s.itemNames }}</span><br>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="pan-btn primary-btn" @click="closeTimeData">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="同步检验项目配置"
      :visible.sync="syncVisible"
      :before-close="closeSync"
      :close-on-click-modal="false"
      width="30%">
      <el-form label-position="top">
        <el-form-item label="请选择存样日期，从这个时间点开始的稳考计划根据相应的取样点更新检验项目配置(注意:两种同步方式:已完成的包括已发起的稳考,若有问题请联系管理员)">
          <el-date-picker
            v-model="startTime"
            align="right"
            type="date"
            placeholder="存样日期"
            style="width: 100%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="同步方式">
          <el-radio v-model="syncWay" label="0">同时改变已完成和未完成</el-radio>
          <el-radio v-model="syncWay" label="1">只改变未完成</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSync">取 消</el-button>
        <el-button type="primary" class="pan-btn primary-btn" :loading="submitingSync" @click="submitSync">确 定</el-button>
      </span>
    </el-dialog>

    <add-or-update-module
    	v-if="addModuleVisible"
    	@close="close('addModuleVisible')"
    	@refreshData="getDataList"
    	:childDataForm="childDataForm" />

    <stability-collocate
      v-if="collocateVisible"
      @close="close('collocateVisible')"
      :childDataForm="childDataForm" />

	</div>
</template>

<script>
	import CommonMethod from '@/views/mixin/common'
	import { CODE_OK } from '@/common/js/config'
	import { getProjectList,getProjectInfo,deleteProject,copyProject,syncStabilityProject } from "@/api/stability"
	import AddOrUpdateModule from './stability-addorupdatemodule'
  import StabilityCollocate from './stability-collocate'
  import { isBlank } from '@/common/js/utils'
	export default {
    name: 'wenkaofangan',
		mixins: [CommonMethod],
		components: {
			AddOrUpdateModule,StabilityCollocate
		},
		data() {
    	return {
        timeData: [],
        showTimeData: false,
        syncVisible: false,
        startTime: '2015-01-01 00:00:00',
        syncWay: '',
        submitingSync: false,
	      dataForm: {
          projectId: null
        },
	      dataList: [],
	      pageIndex: 1,
	      pageSize: 10,
	      totalPage: 0,
	      dataListLoading: false,
	      selectionList: [],
	      addModuleVisible: false,
	      childDataForm: "",
        collocateVisible: false,
        waiteIndex: ''
	    }
  	},
  	mounted() {
  		if (this.isAuth('base:stability:list')) {
  			this.getDataList()
  		}
  	},
  	methods: {
      submitSync() {
        if (isBlank(this.startTime)) {
          this.$message.error('请选择存样时间')
          return
        }
        if (isBlank(this.syncWay)) {
          this.$message.error('请选择同步方式')
          return
        }
        this.submitingSync = true
        const data = {
          projectId: this.waiteIndex,
          startTime: this.startTime,
          syncWay: this.syncWay
        }
        syncStabilityProject(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success(res.msg)
            this.closeSync()
          }else{
            this.$message.error(res.msg)
          }
          this.submitingSync = false
        })
      },
      sync(projectId) {
        this.waiteIndex = projectId
        this.syncVisible = true
      },
      copy(projectId) {
        this.$prompt('请输入新方案名称，注意复制后及时修改，以免影响后面操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          const data = {
            projectId: projectId,
            projectName: value
          }
          copyProject(data).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success("复制成功，请及时修改")
              this.getDataList()
            }else{
              this.$message.error(res.msg)
            }
          })
        }).catch(()=>{})
      },
      getTimeData(i) {
        const params = {
          projectId: this.dataList[i].projectId
        }
        getProjectInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.timeData = res.info.times.map(t => {
              t.standards = t.standards.map(s => {
                this.$set(s,'itemNames',s.items.map(it => {
                  return it.inspectionItemName
                }).join('、'))
                return s
              })
              return t
            })
            this.showTimeData = true
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      closeTimeData() {
        this.showTimeData = false
        this.timeData = []
      },
      closeSync() {
        this.syncVisible = false
        this.startTime = '2015-01-01 00:00:00'
        this.syncWay = ''
        this.waiteIndex = ''
      },
      searchData() {
      	this.pageIndex=1
      	this.getDataList()
      },
      getDataList() {
      	this.dataListLoading = true
      	const params = {
      		page: this.pageIndex,
          limit: this.pageSize,
      		projectName: this.dataForm.projectName || null,
          productName: this.dataForm.productName || null,
          productGmp: this.dataForm.productGmp || null,
          projectId: this.dataForm.projectId || null
      	}
      	getProjectList(params).then(res => {
      		if (res.code === CODE_OK) {
      			this.dataList = res.page.list
      			this.totalPage = res.page.totalCount
      		}else{
      			this.$message.error(res.msg)
      		}
      		this.dataListLoading = false
      	}).catch()
      },
      close(val) {
        this.childDataForm = ""
        this[val] = false
      },
      collocate(row) {
        this.childDataForm = JSON.parse(JSON.stringify(row))
        this.collocateVisible = true
      },
      addModule() {
      	this.childDataForm = ""
      	this.addModuleVisible = true
      },
			updateData(row) {
				this.childDataForm = JSON.parse(JSON.stringify(row))
				this.addModuleVisible = true
			},
			deleteData(id) {
				if (this.selectionList.length == 0 && id == undefined) {
					this.$message.error('请选择至少一个方案')
					return
				}
				let ids = id ? [id] : this.selectionList.map(item => {
					return item.projectId
				})
				let msg = id ? '此操作将永久删除此方案, 是否继续?' : '此操作将永久删除选中的方案, 是否继续?'
				this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
       	}).then(() => {
       		deleteProject(ids).then(res => {
       			if (res.code === CODE_OK) {
       				this.$message({
		            type: 'success',
		            message: '删除成功!'
		          })
       				this.getDataList()
       			}else{
       				this.$message.error(res.msg)
       			}
       		})
        }).catch()
			},
			selectionChange(obj) {
				this.selectionList = obj
			}
  	},
    watch: {
      $route: {
        handler: function (to, from){
          if (to.name === '稳考方案' && to.params.id != null) {
            this.dataForm.projectId = to.params.id
            this.getDataList()
          }
        },
        immediate: true
      }
    }
	}
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: normal;
  }
</style>
